package com.mc.servlet;

import com.mc.bean.College;
import com.mc.bean.Grade;
import com.mc.bean.Student;
import com.mc.service.CollegeService;
import com.mc.service.GradeService;
import com.mc.service.StudentService;
import com.mc.service.impl.CollegeServiceImpl;
import com.mc.service.impl.GradeServiceImpl;
import com.mc.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/studentadd.action")
public class StudentAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StudentService studentService = new StudentServiceImpl();

        CollegeService collegeService = new CollegeServiceImpl();
        GradeService gradeService = new GradeServiceImpl();
        String jsp = req.getParameter("jsp");
        if ("login".equals(jsp)) {
            List<College> collegeList = collegeService.findAll();
            List<Grade> gradeList = gradeService.findAll();
            req.setAttribute("collegelist", collegeList);
            req.setAttribute("gradelist", gradeList);
            req.getRequestDispatcher("student_regist.jsp").forward(req, resp);
            return;
        }
        String sname = req.getParameter("sname");
        String stel = req.getParameter("stel");
        String spassword = req.getParameter("spassword");
        int sage = Integer.parseInt(req.getParameter("sage"));
        String ssex = req.getParameter("ssex");
        int colid = Integer.parseInt(req.getParameter("colid"));
        int gid = Integer.parseInt(req.getParameter("gid"));
        Student student = new Student(sname, stel, spassword, sage, ssex, colid, gid);
        boolean flag = studentService.add(student);
        System.out.println(flag);
        String type = req.getParameter("type");
        if (type.equals("1")) {
            resp.sendRedirect("studentlist.action");
        } else if(type.equals("2")){
            resp.sendRedirect("userlogin.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
